#include "userprog/syscall.h"
#include <stdio.h>
#include <syscall-nr.h>
#include <user/syscall.h>
#include "threads/interrupt.h"
#include "threads/thread.h"

/* This is a skeleton system call handler */

static void syscall_handler (struct intr_frame *);

static int sys_write (int fd, const void *buffer, unsigned size);

void
syscall_init (void) 
{
  intr_register_int (0x30, 3, INTR_ON, syscall_handler, "syscall");
}

static void
syscall_handler (struct intr_frame *f UNUSED) 
{
  int syscall_num = *((int *)f->esp);
  int fd;
  char *buf;
  size_t size;
	
  hex_dump ((int)(f->esp), f->esp, 20, true);
  printf("\n\n");
  switch (syscall_num)
  {
	  case SYS_HALT:
		  power_off ();
		  break;

	  case SYS_EXEC:
		  f->eax = process_execute(*(char **)(f->esp + 4));
		  break;

	  case SYS_WAIT:
	  	  f->eax = process_wait(*(tid_t *)(f->esp + 4));
	  	  break;

	  case SYS_READ:
		  fd = *(int *)(f->esp + 4);
		  buf = *(char **)(f->esp + 8);
		  size = *(size_t *)(f->esp + 12);
		  if (fd == 0)	// STDIN
		  	  f->eax = input_getc();
		  else
		  	  f->eax = -1;
		  break;

	  case SYS_WRITE:
		  fd = *(int *)(f->esp + 4);
		  if (fd == 1)
		  {
			  putbuf (*(char**)(f->esp + 8), *(size_t*)(f->esp + 12));
			  f->eax = *(int*)(f->esp + 12);
		  }
		  else
			  f->eax = -1;
		  break;

	  default:
		  printf("system call! syscall_num: %d is not yet implemented\n", syscall_num);
		  thread_exit ();
		  break;
  }
}
